package com.ljp.chat.controller;

import cn.hutool.core.date.DateUtil;
import com.ljp.chat.entity.Result;
import com.ljp.chat.entity.dto.ChatMsg;
import com.ljp.chat.entity.enums.ChatEnum;
import com.ljp.chat.entity.enums.ResultEnum;
import com.ljp.chat.entity.pojo.ChatUser;
import com.ljp.chat.utils.WsTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Slf4j
@RestController
@ServerEndpoint("/connect/{userBh}/{userName}")
public class ChatroomController {

    @OnOpen
    public void openSession(@PathParam("userBh") String userBh, @PathParam("userName") String userName, Session session) {
        ChatUser chatUser = new ChatUser()
                .setUserBh(userBh)
                .setUserName(userName)
                .setOnlineTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));

        WsTool.LIVING_SESSIONS_CACHE.put(userBh, session);
        WsTool.LIVING_USER_CACHE.put(userBh, chatUser);

        ChatMsg chatMsg = new ChatMsg()
                .setSendUserBh(chatUser.getUserBh())
                .setSendUserXm(chatUser.getUserName())
                .setType(ChatEnum.JOIN_CHAT.getCode());

        WsTool.sendMessageAll(chatMsg);

        //刷新用户列表
        WsTool.refreshOnlineUserList();
    }

    @OnMessage
    public void onMessage(@PathParam("userBh") String userBh, String message) {
        log.info(message);

        //心跳程序
        if ("HeartBeat".equals(message)) {
            return;
        }

        ChatUser chatUser = WsTool.LIVING_USER_CACHE.get(userBh);
        ChatMsg chatMsg = new ChatMsg()
                .setSendUserBh(chatUser.getUserBh())
                .setSendUserXm(chatUser.getUserName())
                .setType(ChatEnum.PUBLIC_MSG.getCode())
                .setMsg(message);

        WsTool.sendMessageAll(chatMsg);
    }

    @OnClose
    public void onClose(@PathParam("userBh") String userBh, Session session) {
        ChatUser chatUser = WsTool.LIVING_USER_CACHE.get(userBh);

        //当前的Session 移除
        WsTool.LIVING_SESSIONS_CACHE.remove(chatUser.getUserBh());
        WsTool.LIVING_USER_CACHE.remove(chatUser.getUserBh());

        //并且通知其他人当前用户已经离开聊天室了
        ChatMsg chatMsg = new ChatMsg().setSendUserBh(chatUser.getUserBh()).setSendUserXm(chatUser.getUserName()).setType(ChatEnum.CLOSE_SOCKET.getCode());
        WsTool.sendMessageAll(chatMsg);

        //刷新用户列表
        WsTool.refreshOnlineUserList();

        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }


    /**
     * Private send result.
     * 一对一私聊
     *
     * @param sendUserBh    the send user bh
     * @param receiveUserBh the receive user bh
     * @param message       the message
     * @return the result
     */
    @GetMapping("/privateSend/{sendUserBh}/to/{receiveUserBh}")
    public Result privateSend(@PathVariable("sendUserBh") String sendUserBh, @PathVariable("receiveUserBh") String receiveUserBh, String message) {
        Session sendSession = WsTool.LIVING_SESSIONS_CACHE.get(sendUserBh);
        Session receiveSession = WsTool.LIVING_SESSIONS_CACHE.get(receiveUserBh);
        ChatUser sendUser = WsTool.LIVING_USER_CACHE.get(sendUserBh);
        ChatUser receiver = WsTool.LIVING_USER_CACHE.get(receiveUserBh);
        ChatMsg chatMsg = new ChatMsg()
                .setSendUserBh(sendUser.getUserBh())
                .setSendUserXm(sendUser.getUserName())
                .setType(ChatEnum.PRIVATE_MSG.getCode())
                .setMsg(message);

        //对发送人发送
        WsTool.sendMessage(sendSession, chatMsg);

        //接受人发送
        WsTool.sendMessage(receiveSession, chatMsg);

        Result result = new Result();
        result.setCode(ResultEnum.SUCCESS.getCode());

        return result;
    }
}
